//
//  SyncTimer.swift
//  EVOP
//
//  Created by LC_WJH on 2017/8/8.
//  Copyright © 2017年 gmc. All rights reserved.
//

import Foundation

public class SyncTimer:NSObject{
    
    
    fileprivate var cb:(()->Void)?
    fileprivate var logTxt:String?
    
    fileprivate var gap:Double = 10;
    
    ///可以修改运行的线程
    public var runAt:DispatchQueue?;
    public var firstRunDelay:TimeInterval = 0;
    
    public func setOnTimerAct(setGap:Double,logTag:String , _cb:@escaping (()->Void)){
        
        if runAt == nil {
            //默认主线程操作
            runAt = DispatchQueue.main;
        }
        
        gap = setGap;
        cb = _cb;
        logTxt = logTag;
    }
    
    
    //MARK:画面数据自动刷新工具
    var autoRefresher:Timer?
    var sourceTimer:DispatchSourceTimer?
    public  func startAutoRefresh(){
        
        
        if runAt == nil {
            return;
        }
        weak var wself = self ;

        stopAutoRefresh();
        sourceTimer = DispatchSource.makeTimerSource(flags: [], queue: runAt);
        sourceTimer?.scheduleRepeating(deadline: DispatchTime.now() + firstRunDelay, interval: gap);
        sourceTimer?.setEventHandler {
            self.cb?();
        }
        sourceTimer?.resume();
        print("Report:\(wself?.logTxt ?? "")自动刷新已经启用");
        
        
    }
    public func stopAutoRefresh(){
        
        weak var wself = self
        if sourceTimer != nil {
            print("Report:\(wself?.logTxt ?? "")自动刷新已经停止");
            sourceTimer?.cancel();
            sourceTimer = nil;
        }
 
        
    }
 
    
}


